<?php

namespace App\Http\Controllers;

use App\Models\AddressBookLabel;
use App\Models\Agreement;
use App\Models\CaseDescribe;
use App\Models\DoctorWorks;
use App\Models\Follow;
use App\Models\AddressBook;
use App\User;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use ZipStream\Exception;


class CaseHistoryController extends BaseController
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
//        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $workId = $request->workId ?? '';
        $doctorId = $request->doctorId ?? '';
        return view('caseHistory', ['workId' => $workId,'doctorId'=>$doctorId,'rands'=>rand(000000,999999)]);
    }
    //各种协议
    public function agreement(Request $request)
    {
        $type = $request->type ?? '';
        $content = (new Agreement())->where([['type', '=', $type]])->first();
        if(!empty($content)){
            $content = $content->toArray();
        }
        return view('agreement', ['content' => $content]);
    }

    //上架也行(暂时的
    public function upagreement(Request $request)
    {
        return view('shelve_sagreement');
    }

    /***
     * @param Request $request
     * @return mixed
     * 上传图片
     */
    public function inputFile(Request $request)
    {
        $image = $request->file('imgFile');
        if (empty($image)) {
            return $this->ResultJson(0, '提交的数据不能为空', []);
        }
        $imagePath = 'image/' . date("Y-m-d") . DIRECTORY_SEPARATOR . strtotime("now") . rand() . '.png';
        Storage::disk('public')->put($imagePath, file_get_contents($image));
        $data = ['imagePath' => $imagePath];
        return $this->ResultJson(1, '上传成功', $data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|string
     * 插入数据
     */
    public function inputInfo(Request $request)
    {
        $phone = $request->phone ?? '';
        $name = $request->name ?? '';
        $sex = $request->sex ?? '';
        $age = $request->age ?? '';
        $type = $request->type ?? '';
        $image = $request->image ?? '';
        $describe = $request->describe ?? '';
        $Pcode = $request->smsCode ?? '';
        $workId = $request->workId ?? '';
        $doctorId = $request->doctorId ?? '';
        $rands = $request->rands ?? '';
        $case_id = $request->case_id ?? '';

        if($rands == Cache::get($phone."_rands")){
            return $this->ResultJson(0, '不能重复提交数据', []);
        }
        $work_inf = (new DoctorWorks())->where([['id','=',$workId]])->first();
        if(empty($work_inf)){
            return $this->ResultJson(0, '该工作室不存在', []);
        }
        Cache::add($phone."_rands",$rands,10);
        if (!Tool::checkMobile($phone)) {
            return $this->ResultJson(0, '请填写正确的手号码', []);
        }
        //判断用户是否发送短信验证请求
        if (empty($this->getCode($phone))) {
            return $this->ResultJson(0, '请发送短信验证码', []);
        }
        //需要检查验证码是否过期
        $code = Tool:: GetSmsvalidator($phone);
        if (empty($code)) {
            return $this->ResultJson(0, '验证码已经过期', []);
        }
        //检查验证码是否正确
        if ($Pcode != $code) {
            return $this->ResultJson(0, '验证码错误', []);
        }
        //更新验证码为验证过了
        $this->SetCode($phone, $code);
        //创建用户信息
        $pass = 123456;
        $api_token = Tool::RandomToken($phone);
        $data['name'] = $name;
        $data['sex'] = $sex;
        $data['age'] = $age;
        $data['phone'] = $phone;
        $data['password'] = bcrypt($pass);
        $data['api_token'] = $api_token;
        $date = date("Y-m-d H:i:s");
        $res['user_name'] = $name;
        $res['sex'] = $sex;
        $res['age'] = $age;
        $res['type'] = $type;
        $res['image'] = \GuzzleHttp\json_decode($image);
        $res['describe'] = $describe;
        $res['phone'] = $phone;
        $res['doctor_id'] = $doctorId;
        $res['work_id'] = $workId;
        $res['created_at'] = $date;
        $res['updated_at'] = $date;
        if($case_id >0){
            try {
                DB::beginTransaction();
                $case = new CaseDescribe();
                $info = User::where([['phone', '=', $phone]])->first();
                $res['user_id'] = $info->id;
                //查看该用户是否已有病例
                $case_info = $case->where([['id', '=', $case_id]])->first();
                $lt = AddressBook::where([['work_id', '=', $res['work_id']], ['user_id', '=', $info->id], ['case_id', '=', $case_info->id]])->first();
                if ($lt) {
                    $res['case_id'] = $case_info->id;
                    $res['image'] = $image;
                    AddressBook::where([['id', '=', $lt->id]])->update($res);
                    $bk_id = $lt->id;
                } else {
                    $res['case_id'] = $case_info->id;
                    $ads = AddressBook::create($res);
                    $bk_id = $ads->id;
                }
                $books = AddressBook::where([['id', '=', $bk_id]])->first();
                //给打默认标签
                $tl['address_book_id'] = $books->id;
                $tl['address_book_label_id'] = (new AddressBookLabel())->where([['is_default', '=', 1], ['num', '=', $type], ["work_id", '=', $res['work_id']]])->value('id');
                $tl['work_id'] = $res['work_id'];
                $tl['created_at'] = date("Y-m-d H:i:s", time());
                $tl['updated_at'] = date("Y-m-d H:i:s", time());
                $ha = DB::table("c_address_book_relate_labels")->where([['address_book_id', '=', $tl['address_book_id']], ['address_book_label_id', '=', $tl['address_book_label_id']], ['work_id', '=', $tl['work_id']]])->first();
                if (empty($ha)) {
                    DB::table("c_address_book_relate_labels")->insertGetId($tl);
                }
                //查看是否关注了该工作室
                $foll = new Follow();
                $follw_work = $foll->where([['work_id', '=', $workId], ['user_id', '=', $res['user_id']], ['type', '=', 1]])->first();
                if (empty($follw_work)) {
                    $foll->type = 1;
                    $foll->work_id = $workId;
                    $foll->user_id = $res['user_id'];
                    $foll->save();
                }
                Db::commit();
            } catch (Exception $exception) {
                DB::rollBack();
                return $exception->getMessage();
            }
        }else{
            try {
                DB::beginTransaction();
                $case = new CaseDescribe();
                $info = User::where([['phone','=',$phone]])->first();
                if(empty($info)){
                    $user = User::create($data);
                    $res['user_id'] = $user->id;
                    //创建病例
                    $case->name = $name;
                    $case->sex = $sex;
                    $case->age = $age;
                    $case->picture =  $res['image'];
                    $case->user_id =   $res['user_id'];
                    $case->relation =  "本人";
                    $case->describe =  $describe;
                    $case->save();
                    $res['case_id'] = $case->id;
                    $ads = AddressBook::create($res);
                    $bk_id = $ads->id;
                    //登录后写入redis api_token
                    //环信聊天用户信息注册
                    $tool = Tool::getUserNameForIm(['type' => 1, 'user_id' => $user->id]);
                    (new Easemob())->createUser($tool['username'], $tool['password']);
                    //注册问卷
                    (new SurveysController())->register(['type' => 1, 'user_id' => $user->id]);
                }else{
                    $res['user_id'] = $info->id;
                    //查看该用户是否已有病例
                    $case_info = $case->where([['name','=',$name],['sex','=',$sex],['user_id','=',$info->id]])->first();
                    if(empty($case_info)){
                        //创建病例
                        $case->name = $name;
                        $case->sex = $sex;
                        $case->age = $age;
                        $case->picture =  $res['image'];
                        $case->user_id =   $res['user_id'];
                        $case->relation =  "本人";
                        $case->describe =  $describe;
                        $case->save();
                        $res['case_id'] = $case->id;
                        $ads = AddressBook::create($res);
                        $bk_id = $ads->id;
                    }else{
                        $lt = AddressBook::where([['work_id','=',$res['work_id']],['user_id','=',$info->id],['case_id','=',$case_info->id]])->first();
                        if($lt){
                            $res['case_id'] = $case_info->id;
                            $res['image'] = $image;
                            AddressBook::where([['id','=',$lt->id]])->update($res);
                            $bk_id = $lt->id;
                        }else{
                            $res['case_id'] = $case_info->id;
                            $ads = AddressBook::create($res);
                            $bk_id = $ads->id;
                        }
                    }
                }
                $books = AddressBook::where([['id','=',$bk_id]])->first();
                //给打默认标签
                $tl['address_book_id'] = $books->id;
                $tl['address_book_label_id'] = (new AddressBookLabel())->where([['is_default','=',1],['num','=',$type],["work_id",'=',$res['work_id']]])->value('id');
                $tl['work_id'] = $res['work_id'];
                $tl['created_at'] = date("Y-m-d H:i:s",time());
                $tl['updated_at'] = date("Y-m-d H:i:s",time());
                $ha = DB::table("c_address_book_relate_labels")->where([['address_book_id','=', $tl['address_book_id']],['address_book_label_id','=',$tl['address_book_label_id']],['work_id','=', $tl['work_id']]])->first();
                if(empty($ha)){
                    DB::table("c_address_book_relate_labels")->insertGetId($tl);
                }
                //查看是否关注了该工作室
                $foll  = new Follow();
                $follw_work = $foll->where([['work_id','=',$workId],['user_id','=',$res['user_id']],['type','=',1]])->first();
                if(empty($follw_work)){
                    $foll->type = 1;
                    $foll->work_id = $workId;
                    $foll->user_id = $res['user_id'];
                    $foll->save();
                }
                Db::commit();
            } catch (Exception $exception) {
                DB::rollBack();
                return $exception->getMessage();
            }
        }
        return $this->ResultJson(1, '提交成功!', []);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 通过手机号获取个人病例
     */
    public function getCaseDescribes(Request $request)
    {
        $res = $request->input();
        $user = (new User())->where([['phone', '=', $res['phone']]])->first();
        if (!empty($user)) {
            $case = (new CaseDescribe())->where([['user_id', '=', $user->id]])->get();
            if (!empty($case)) {
                return $this->ResultJson(1, '获取成功!', $case->toArray());
            }
            return $this->ResultJson(0, '无!', []);
        }
        return $this->ResultJson(0, '无!', []);
    }

    /***
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * 获取个人病例
     */
    public function getCaseDetail(Request $request)
    {
        $res = $request->input();
        $case = (new CaseDescribe())->where([['id', '=', $res['case_id']]])->first();
        if (!empty($case)) {
            $caseInfo = $case->toArray();
            if (!empty($caseInfo['picture'])) {
                $url = Url::getHttpHost();
                if (count($caseInfo['picture']) == 1 && $caseInfo['picture'][0] == "") {
                    $caseInfo['picture'] = [];
                } else {
                    foreach ($caseInfo['picture'] as $k => $value) {
                        if (empty(trim($value))) {
                            continue;
                        }
                        $caseInfo['picture'][$k] = $url . 'upload/' . $value;
                    }
                }
            }
            return $this->ResultJson(1, '获取成功!', $caseInfo);
        }
        return $this->ResultJson(0, '无!', []);
    }

}
